package com.app.view_controller;

import java.util.ArrayList;
import java.util.zip.Inflater;

import com.app.alarm.R;
import com.app.model.AlarmDataManager;
import com.app.model.AlarmDataManager.AlarmLoader;
import com.app.util.ApplicationMediator;
import com.app.util.MessageListenerAdapter;
import com.app.view_controller.custom_view.nhaarman.listviewanimations.itemmanipulation.OnDismissCallback;
import com.app.view_controller.custom_view.nhaarman.listviewanimations.itemmanipulation.swipedismiss.SwipeDismissAdapter;
import com.app.view_controller.custom_view.nhaarman.listviewanimations.swinginadapters.prepared.SwingBottomInAnimationAdapter;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.gesture.GestureOverlayView;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.ViewTreeObserver.OnScrollChangedListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

@SuppressLint("ValidFragment")
@SuppressWarnings("unused")
public class ListFragment extends Fragment implements OnClickListener, OnDismissCallback, OnGlobalLayoutListener {

	protected static final boolean DEBUG = true;
	protected static final String TAG = "LISTFRAGMENT";
	private ListView mListView;
	private View mColorFilterView;
	private ApplicationMediator mSingleton;

	private ActionBar mBar;
	private ImageButton mAddAlarmButton;
	private ArrayList<AlarmDataManager> mList;
	private ListAdapter mAdapter;
	private Button mEraseButton;
	private AlarmDataManager alarm;
	private SwingBottomInAnimationAdapter swingAdapter;
	private GestureOverlayView mGesture;
	private GestureDetector mDetector;
	private RelativeLayout mActionBarBackground;
	private LinearLayout mActionBarTouchOverlay;
	private boolean onCreateCalled = false;
	private UpdateListReceiver mReceiver;
	public static final String ACTION_UPDATE_LIST = "com.app.view_controller.ListAdapter.ACTION_UPDATE_LIST";

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		mBar = getActivity().getActionBar();
		setHasOptionsMenu(true);
		mSingleton = ApplicationMediator.getInstance();
		onCreateCalled = true;
		// Listener that removes the color filter when the dialog is closed
		mSingleton.setMessagesListener(this, ContentActivity.START_DIALOG_CLOSURE, new MessageListenerAdapter() {
			@Override
			public void onMessageReceived() {
				if (DEBUG)
					Log.d(TAG, "Remove overlay color");
				mActionBarTouchOverlay.animate().translationYBy(mActionBarTouchOverlay.getHeight())
						.setDuration(ContentActivity.ANIMATION_DURATION_MEDIUM);
				mActionBarBackground.animate().translationYBy(mActionBarTouchOverlay.getHeight())
						.setDuration(ContentActivity.ANIMATION_DURATION_MEDIUM);
				super.onMessageReceived();
				mColorFilterView.setAlpha(1f);
				Animator anim = ObjectAnimator.ofFloat(mColorFilterView, View.ALPHA, 1f, 0f);
				anim.setDuration(300);

				anim.addListener(new AnimatorListenerAdapter() {

					@Override
					public void onAnimationEnd(Animator animation) {
						mColorFilterView.setVisibility(View.GONE);
					}
				});
				anim.start();
				super.onMessageReceived();
			}
		});
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (DEBUG)
			Log.d(TAG, "OnCreateListView");
		View view = inflater.inflate(R.layout.fragment_list, container, false);
		mListView = (ListView) view.findViewById(R.id.listView1);
		mColorFilterView = view.findViewById(R.id.view_color_filter);

		mList = AlarmLoader.getStoredAlarmList(getActivity());
		mList.add(0, null);
		mAdapter = new ListAdapter(getActivity(), R.layout.cell_adapter, mList, mListView, mColorFilterView, this);
		SwipeDismissAdapter dismissAdapter = new SwipeDismissAdapter(mAdapter, this);
		swingAdapter = new SwingBottomInAnimationAdapter(dismissAdapter, 400, 300);
		mListView.setAdapter(swingAdapter);
		swingAdapter.setAbsListView(mListView);
		if (savedInstanceState != null)
			mColorFilterView.setVisibility(savedInstanceState.getInt(ContentActivity.IS_COLORFILTER_VISIBLE, View.GONE));

		mActionBarBackground = ((ContentActivity) getActivity()).getApplicationActionBar();
		mActionBarTouchOverlay = (LinearLayout) view.findViewById(R.id.action_bar_l_touch_overlay);
		mActionBarTouchOverlay.getViewTreeObserver().addOnGlobalLayoutListener(this);
		mAddAlarmButton = (ImageButton) mActionBarTouchOverlay.findViewById(R.id.actionbar_add_alarm_button);
		mEraseButton = (Button) mActionBarTouchOverlay.findViewById(R.id.erase_button);
		mEraseButton.setOnClickListener(this);
		mAddAlarmButton.setOnClickListener(this);
		mListView.setOnScrollListener(new OnScrollListener() {

			private int scrollState;
			private boolean invisible = false;
			private ObjectAnimator mActionBarBackgroundAnimator;
			private ObjectAnimator mActionBarTouchOverlayAnimator;;

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				this.scrollState = scrollState;

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				if (firstVisibleItem == 1 && invisible == false) {
					if (mActionBarBackgroundAnimator != null && mActionBarBackgroundAnimator.isRunning())
						mActionBarBackgroundAnimator.cancel();
					mActionBarBackgroundAnimator = ObjectAnimator.ofFloat(mActionBarBackground, "translationY", -mActionBarBackground.getHeight());
					mActionBarBackgroundAnimator.start();
					if (mActionBarTouchOverlayAnimator != null && mActionBarTouchOverlayAnimator.isRunning())
						mActionBarTouchOverlayAnimator.cancel();
					mActionBarTouchOverlayAnimator = ObjectAnimator.ofFloat(mActionBarTouchOverlay, "translationY",
							-mActionBarTouchOverlay.getHeight());
					mActionBarTouchOverlayAnimator.start();
					invisible = true;
				}
				if (firstVisibleItem == 0 && invisible == true) {
					if (mActionBarBackgroundAnimator != null && mActionBarBackgroundAnimator.isRunning())
						mActionBarBackgroundAnimator.cancel();
					mActionBarBackgroundAnimator = ObjectAnimator.ofFloat(mActionBarBackground, "translationY", 0);
					mActionBarBackgroundAnimator.start();
					if (mActionBarTouchOverlayAnimator != null && mActionBarTouchOverlayAnimator.isRunning())
						mActionBarTouchOverlayAnimator.cancel();
					mActionBarTouchOverlayAnimator = ObjectAnimator.ofFloat(mActionBarTouchOverlay, "translationY", 0);
					mActionBarTouchOverlayAnimator.start();
					invisible = false;
				}
			}
		});

		return view;
	}

	@Override
	public void onResume() {

		mReceiver = new UpdateListReceiver();
		IntentFilter filter = new IntentFilter(ACTION_UPDATE_LIST);
		getActivity().registerReceiver(mReceiver, filter);
		super.onResume();
	}

	class UpdateListReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(ListFragment.ACTION_UPDATE_LIST)) {
				if (DEBUG)
					Log.d(TAG, "UPDATE LIST ADAPTER CALLED");
				ArrayList<AlarmDataManager> list = AlarmLoader.getStoredAlarmList(getActivity());
				for (int i = 0; i < list.size(); i++) {
					mAdapter.remove(mAdapter.getItem(i + 1));
					mAdapter.add(i + 1, list.get(i));
				}
				mAdapter.notifyDataSetChanged();
			}
	//		mListView.requestLayout();
		}
	}

	public LinearLayout getActionBarTouchOverlay() {
		return mActionBarTouchOverlay;
	}

	@Override
	public void onGlobalLayout() {
		if (onCreateCalled) {
			mActionBarTouchOverlay.setY(-mActionBarTouchOverlay.getHeight());
			mActionBarTouchOverlay.animate().translationYBy(mActionBarTouchOverlay.getHeight());
		}
		onCreateCalled = false;

	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putInt(ContentActivity.IS_COLORFILTER_VISIBLE, mColorFilterView.getVisibility());
		super.onSaveInstanceState(outState);
	}

	@Override
	public void onClick(View v) {
		final int id = v.getId();
		if (id == mAddAlarmButton.getId()) {
			AlarmDataManager alarm = new AlarmDataManager(getActivity());
			alarm.savetoStorage();
			mList.add(alarm);
			mAdapter.notifyDataSetChanged();
		}
		if (id == mEraseButton.getId()) {
			AlarmDataManager mAlarm = mAdapter.getItem(1);
			AlarmDataManager.callAlarmNow(getActivity(), mAlarm.getAlarmId());
		}
	}

	@Override
	public void onDismiss(AbsListView listView, int[] reverseSortedPositions) {
		if (DEBUG)
			Log.d(TAG, "Removed a row with a dismiss gesture");
		for (int i = 0; i < reverseSortedPositions.length; i++) {
			AlarmLoader.removeAlarmFromStorage(mAdapter.getItem(reverseSortedPositions[i]), getActivity());
			mAdapter.remove(mAdapter.getItem(reverseSortedPositions[i]));
		}

	}

	@Override
	public void onDestroy() {
		getActivity().unregisterReceiver(mReceiver);
		super.onDestroy();
	}
	// @Override
	// public void onItemClick(AdapterView<?> arg0, View cell, int position,
	// long arg3) {
	// if(position!=0)
	// mAdapter.switchToDialog(cell, position);
	// }

}
